package com.witmed.lib_http.download

import android.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.File
import java.io.FileOutputStream
import java.io.InputStream

object DownloadManager {
    fun download(url:String,file:File):Flow<DownloadStatus>{
        return flow {
            val request = Request.Builder().url(url).addHeader("Accept-Encoding","identity").get().build()
            val response = OkHttpClient.Builder().build().newCall(request).execute()

            if(response.isSuccessful){
                Log.i("===response",response.toString())
//                var contentLength = response.header("content-length")?.toDouble();
                var contentLength =response.headers().get("Content-Length")
                response.body()?.let {b->
                    //获取文件大小
                    val length=b.contentLength()
                    file.outputStream().let {
                        val inputstream = b.byteStream()

                        inputstream.copyTo(it){clength->
                            Log.i("===","当前长度：$clength,总长：$contentLength")
                            val progress=clength/length!!*100
//                            DownloadStatus.Progress(progress = progress.toInt())
                            emit(value = DownloadStatus.Progress(progress = progress.toInt()))

                        }
                    }
                    emit(DownloadStatus.Done(file))
                }
            }
        }.flowOn(Dispatchers.IO)
    }

      inline fun InputStream.copyTo(out: FileOutputStream, bufferSize: Int= DEFAULT_BUFFER_SIZE, progress:(Long)->Unit): Long {
          var bytelen:Long=0
        val byteArray=ByteArray(bufferSize)
        var read = read(byteArray)
        while (read>=0){
            out.write(byteArray,0,read)
            bytelen+=read
            read=read(byteArray)
            progress(bytelen)
        }
        return bytelen
    }
}


